//下一个要工作的fiber
let nextUnitOfWork = null

//work in progress 正在工作中的
//正在工作中的fiber root

function updateHostComponent(workInprogress) {
  if (!workInprogress.stateNode) {
    workInprogress.stateNode = createNode(workInprogress)
  }

  //协调子节点
  recocileChildren(workInprogress, workInprogress.props.children)
}

function recocileChildren(workInprogress, children) {
  let previousNewFiber = null
  for (let i = 0; i < children.length; i++) {
    const child = children[i]
    let newFiber = {
      type: child.type,
      key: child.key,
      props: child.props,
      stateNode: null, //如果是原生标签节点，这个值存储dom节点
      child: null, //第一个子节点
      sibling: null, //下一个兄弟节点
      return: workInProgress, //父节点
    }
  }

  if (i === 0) {
    workProgress.child = newFiber
  } else {
    previousNewFiber.sibling = newFiber
  }
  previousNewFiber = newFiber
}

function performUnitOfwork(workInprogress) {
  // step1: 处理fiber
  updateHostComponent(workInprogress)

  //step2: 返回下一个要处理的fiber
  if (workInprogress.child) {
    return workInprogress.child
  }

  let next = workInprogress
  while (next) {
    if (next.sibling) {
      return next.sibling
    }
    next = next.return
  }
}

//更新fiber
function wookLoop() {
  //timeRemaining获取浏览器剩余空闲剩余时间
  while (nextUnitOfWork && idleDeadline.timeRemaining() > 1) {
    //处理当前fiber,并且返回下一个要处理的fiber
    nextUnitOfWork = performUnitOfwork(nestUnitOfwork)
  }

  //commitRoot
  if (!nextUnitodWork && wipRoot) {
    //vnode_>node,更新到container中
    commitRoot()
  }
}

requestIdCallback(workLoop)

function commitRoot() {
  commitWorker(wipRoot.child)
  wipRoot = null
}

function commtWorker(workInprogress) {
  if (!workInprogress) return

  let parentNodeFiber = workInProgress.return

  let parentNode = parentNodeFiber.stateNode
  if (workInprogress.stateNode) {
    parentNode.appendChild(workInprogress.stateNode)
  }

  //step2: 提交workInProgress.child
  commtWorker(workInProgress.children)
  commtWorker(workInProgress.sibling)
}
